import os
from maix import video, time, image, camera, display, app
import datetime

class VideoRecorder:
    def __init__(self, width=1920, height=1080):
        self.width = width
        self.height = height
        self.encoder = None
        self.start_time = None
        self.file_path = None
        self.record_duration = 60  # 默认录制时长为60秒
        self.is_recording = False  # 添加录制状态标志
        
    def create_directory_structure(self):
        """创建按年/月/日结构的目录"""
        now = datetime.datetime.now()
        year = str(now.year)
        month = f"{now.month:02d}"
        day = f"{now.day:02d}"
        
        # 构建目录路径: year/month/day
        dir_path = os.path.join("/root/videos", year, month, day)
        
        # 创建目录（如果不存在）
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
            
        return dir_path
    
    def generate_filename(self):
        """生成按时间命名的文件名"""
        now = datetime.datetime.now()
        time_str = now.strftime("%H_%M")  # 小时_分钟
        filename = f"{time_str}.mp4"
        return filename
    
    def start_recording(self):
        """开始录制视频"""
        # 创建目录结构
        dir_path = self.create_directory_structure()
        
        # 生成文件名
        filename = self.generate_filename()
        
        # 完整文件路径
        self.file_path = os.path.join(dir_path, filename)
        
        # 创建编码器，指定格式为FMT_YVU420SP
        self.encoder = video.Encoder(self.file_path, self.width, self.height, format=image.Format.FMT_YVU420SP)
        
        # 记录开始时间
        self.start_time = time.ticks_ms()
        self.is_recording = True
        
        print(f"开始录制视频: {self.file_path}")
        
    def stop_recording(self):
        """停止录制视频"""
        if self.encoder and self.is_recording:
            # 释放编码器资源
            try:
                self.encoder.finish()  # 正确结束编码器
            except:
                pass  # 忽略可能的异常
            self.encoder = None
            print(f"停止录制视频: {self.file_path}")
            self.file_path = None
            self.start_time = None
            self.is_recording = False
    
    def is_recording_time_up(self):
        """检查是否达到录制时长"""
        if self.start_time is None:
            return False
        return (time.ticks_ms() - self.start_time) >= (self.record_duration * 1000)
    
    def set_record_duration(self, duration_seconds):
        """设置录制时长（秒）"""
        self.record_duration = duration_seconds

def record_video_segment(img, recorder):
    """
    录制视频片段的函数，便于在main.py中调用
    
    Args:
        img: 图像对象
        recorder: VideoRecorder实例
        
    Returns:
        bool: 是否完成了一个视频片段的录制
    """
    # 如果没有开始录制，则开始新的录制
    if not recorder.is_recording:
        recorder.start_recording()
    
    # 编码当前图像
    if recorder.encoder:
        try:
            # 确保图像格式为编码器支持的格式
            if img.format() != image.Format.FMT_YVU420SP:
                img = img.to_format(image.Format.FMT_YVU420SP)
            # 检查图像尺寸是否匹配
            if img.width() != recorder.width or img.height() != recorder.height:
                img = img.resize(recorder.width, recorder.height)
            recorder.encoder.encode(img)
        except Exception as e:
            print(f"编码帧时出错: {e}")
            # 如果编码失败，尝试重新开始录制
            recorder.stop_recording()
            return False
    
    # 检查是否达到录制时长
    if recorder.is_recording_time_up():
        recorder.stop_recording()
        return True  # 完成了一个视频片段的录制
    
    return False  # 仍在录制中

def stop_video_recording(recorder):
    """
    外部控制停止视频录制的函数
    
    Args:
        recorder: VideoRecorder实例
    """
    recorder.stop_recording()